import json
import re

import requests
from urllib.parse import urljoin

import urllib3.util


class Check:
    def __init__(self, lzm,version):
        self.url = lzm
        self.Version = version
        self.filelist = []

    @staticmethod
    def _gethtml(url):
        headers = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"}
        html = requests.get(url,headers=headers).text
        pwd = re.findall("password=(.+)",str(url))[0]
        t = re.findall("'t':(.*?),",html)[0]
        k = re.findall("'k':(.*?),",html)[0]
        fid = re.findall("'fid':(\d+),",html)[0]
        uid = re.findall("'uid':'(\d+)',",html)[0]
        # print(f"{t}(.*?);",k)
        timer = re.findall(f"var {t} = '(\d+)';", html)[0]
        key = re.findall(f"var {k} = '(.*?)';",html)[0]
        postapi = re.findall(f"url : '(.*?)',",html)[0]
        postapi = urljoin(url, postapi)
        # print(fid,uid,timer,key)
        # print(pwd)
        data = {
            'lx': 2,
            'fid': fid,
            'uid': uid,
            'pg': 1,
            'rep': '0',
            't': timer,
            'k': key,
            'up': 1,
            'ls': 1,
            'pwd': pwd
        }
        headers["Referer"] = url
        headers['Content-Type']="application/x-www-form-urlencoded"
        res = requests.post(postapi,data=data,headers=headers).text
        # print(res)
        jsonmap = json.loads(res)
        if jsonmap['zt'] == 1:
            return jsonmap['text']
        else:
            print(jsonmap['info'])

    def getfilelist(self):
        filelist = self._gethtml(self.url)
        for item in filelist:
            # 添加 拼接后的链接
            item['fileurl'] = urljoin(self.url,item['id'])
        self.filelist = filelist
        return filelist

    def CheckVersion(self):
        filelist = self.getfilelist()
        filename = filelist[0]['name_all']
        fileurl = filelist[0]['fileurl']
        xx = re.findall(f'v(\d)\.(\d)\.(\d)\..+',filename,re.IGNORECASE)[0]
        version = re.findall(f'v(\d)\.(\d)\.(\d)',self.Version,re.IGNORECASE)[0]
        # print(xx, version)
        if xx[0] != "" and version[0] != "":
            if xx[0] > version[0]:
                print("更新0")
            else:
                if xx[1] > version[1]:
                    print("更新1")
                else:
                    if xx[2] > version[2]:
                        print(filename,"更新2",fileurl)
                    else:
                        print("最新不需要更新!")
        else:
            print(xx , version)


class Filelist:
    def __init__(self,filelist):
        self.list = filelist




__version__ = '0.1'